const express=require('express')
const app=express();
const cors=require('cors')
const joi = require('joi');
app.use(cors())
app.use(express.urlencoded({extended:false}))
// 在路由之前封装res.cc这个函数目的是发送错误时返回错误信息
app.use('/uploads',express.static('./uploads'))
app.use((req,res,next)=>{
    res.cc=function(err,status=1){
        res.send({
            status,
            message:err instanceof Error?err.message:err
        })
    }
    next()
})
const expressJWT=require('express-jwt')
const config=require('./config')
app.use(expressJWT({secret:config.jwtSecretKey}).unless({path:[/^\/api/]}))
// 导入路由
const userRouter=require('./router/user')
app.use('/api',userRouter)
const userinfoRouter=require('./router/userinfo')
app.use('/my', userinfoRouter)
const artCateRouter=require('./router/artcate')
app.use('/my/article', artCateRouter)
const articleRouter=require('./router/article')
app.use('/my/article', articleRouter)
app.use((err,req,res,next)=>{
    // 验证失败导致的
if(err instanceof joi.ValidationError)return res.cc(err)
if(err.name==='UnauthorizedError')return res.cc('身份认证失败')
// 未知的错误
return res.cc(err)
})
app.listen(3007,()=>{
    console.log('api server running at http://127.0.0.1:3007');
})